package gov.pbc.nn.kjgl.software.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.bstek.uflo.client.service.ProcessClient;

import gov.pbc.nn.core.dao.AbstractHibernateDao;
import gov.pbc.nn.core.dao.PbcnnCoreHibernateDao;
import gov.pbc.nn.kjgl.entity.Project;
import gov.pbc.nn.uflo.entity.Opinion;

@Repository
public class KjcShDao extends AbstractHibernateDao {

	@Autowired
	@Qualifier(ProcessClient.BEAN_ID)
	private ProcessClient processClient;

	@Resource(name = PbcnnCoreHibernateDao.BEAN_ID)
	private PbcnnCoreHibernateDao CoreHibernateDao;

	@Autowired
	private ProjectDao projectDao;

	// public List<Opinion> loadOpinion(String bussinessId) {
	// String hql = "from Opinion where busKey=:bussinessId and invalid=false";
	// Map<String, Object> map = new HashMap<>();
	// map.put("bussinessId", bussinessId);
	// return this.query(hql, map);
	// }

	public String[] getOpinionSign(String businessId, String processInstanceId, String taskId) throws Exception {
		// 取流程变量
		Project p = projectDao.getProjectById(businessId);
		String hldusername = p.getZgywhldUsername();
		String hql = "select opinionImg from " + Opinion.class.getName()
				+ " where invalid=false and busKey=:busKey and username=:username and taskId=:taskId";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("busKey", businessId);
		if (taskId == null) {
			return null;
		}
		map.put("taskId", Long.valueOf(taskId));
		// 查询业务行领导如果为空则 返回 null
		map.put("username", hldusername);
		List<Object> list = CoreHibernateDao.query(hql, map);
		byte[] hldusernameSign = (byte[]) (list.isEmpty() ? null : list.get(0));

		String hldusernameSignStr = null;
		if (hldusernameSign != null) {
			String sign = Base64.encodeBase64String(hldusernameSign);
			hldusernameSignStr = "data:image/jpg;base64," + sign;
		}
		// 返回值一个数组 返回主管行领导和业务行领导
		String[] result = new String[2];
		result[0] = hldusernameSignStr;

		return result;
	}
}